from PIL import Image
import pytesseract
from selenium import webdriver
import time
import re
# 导入发送网络请求的库 requests
import requests

"""	
模拟登录，破解字母数字图片验证码	
目标网站：https://so.gushiwen.org	
"""


# headers = {
#     "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"
# }


class Gushiwen(object):
    def __init__(self):
        self.url = "https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx"
        self.urls = "https://so.gushiwen.org/RandCode.ashx"
        self.headers = {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"
        }
        self.session = requests.session()
        self.driver = webdriver.Chrome()
        # 窗口自定义尺寸
        self.driver.maximize_window()
        # self.driver.set_window_size(500, 800)
        self.driver.implicitly_wait(3)
        self.user = input("请输入账号")
        self.pwd = input("请输入密码")
        self.codes = input("请输入密码")

    # 初始化登录登录
    def get_login(self):
        self.driver.get(self.url)
        print(self.driver.window_handles)
        self.driver.find_element_by_id("email").send_keys(self.user)
        self.driver.find_element_by_id("pwd").send_keys(self.pwd)

        time.sleep(4)

    # 下载识别验证码图片函数
    def get_screenshot(self):
        # # 生成验证码图片url
        # # ce = self.driver.get(self.urls)
        # # 通过session发送get请求，获取验证码
        # resp = self.session.get(self.urls, headers=self.headers)
        # # 将验证码保证到本地
        # with open(r"./test.jpg", 'wb') as f:
        #     f.write(resp.content)
        # # 打开验证码图片文件
        # im = Image.open(r"./test.jpg")
        # # 基本处理，灰度处理，提升识别准确率
        # im = im.convert("L")
        # # 保存处理后的图片
        # im.save("test.jpg")
        # # 利用pytesseract进行图片内容识别
        # text = pytesseract.image_to_string(im)
        # # 去除识别结果中的非数字/字母内容
        # text = re.sub("\W", "", text)
        # # 返回验证码内容
        # print(text)
        # return text

        self.driver.save_screenshot('picture.png')
        ce = self.driver.find_element_by_xpath('//*[@id="imgCode"]')
        print(ce)
        print(ce.location)
        location = ce.location
        size = ce.size
        print(size)
        rangle = (int(location['x'] + 101),
                  int(location['y'] + 53),
                  int(location['x'] + size['width'] + 200),
                  int(location['y'] + size['height'] + 60))  # 写成我们需要截取的位置坐标

        time.sleep(1)
        im = Image.open('./picture.png')
        time.sleep(1)
        im = im.crop(rangle)  # 使用Image的crop函数，从截图中再次截取我们需要的区域
        # im = im.convert('RGB')
        time.sleep(1)
        # 这里就是截取到的验证码图片
        im = im.convert("L")

        # 保存处理后的图片
        im.save('./picture2.png')
        # 引入pytesseract识别图片中的验证码
        im = Image.open('./picture2.png')
        # 利用 pytesseract 进行图片内容识别
        time.sleep(1)
        text = pytesseract.image_to_string(im)
        # 去除识别结果中的非数字/字母内容
        # text = re.sub("\W", "", text)
        print(text)
        self.codes = text
        self.driver.find_element_by_id("code").send_keys(self.codes)

    # 运行
    def run(self):
        # 登录
        self.get_login()
        # 验证码识别
        self.get_screenshot()
        time.sleep(20)

    # 关闭
    # def Sclist(self):
    #     # self.driver.quit()


if __name__ == '__main__':
    Gsw = Gushiwen()
    Gsw.run()
    # Gsw.Sclist()
